package eva.savant.core.secure

import groovy.util.logging.Slf4j
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Slf4j
public class InvalidSessionStrategy implements org.springframework.security.web.session.InvalidSessionStrategy {

  def String invalidSessionUrl

  @Override
  public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    def ajaxRedirect = 'partial/ajax'.equals(request.getHeader('faces-request'))

    if(ajaxRedirect) {

      def redirectUrl= request.contextPath + invalidSessionUrl

      log.debug('Session expired due to ajax request, redirecting to ', redirectUrl)

      def ajaxRedirectXml= createAjaxRedirectXml(redirectUrl)

      log.debug('Ajax partial response to redirect: ', ajaxRedirectXml)

      response.setContentType('text/xml')

      response.writer.write(ajaxRedirectXml)

    } else {

      def requestURI= getRequestUrl(request)

      log.debug('Session expired due to non-ajax request, starting a new session and redirect to requested url ',requestURI)

      request.getSession(true)

      response.sendRedirect(requestURI)
    }

  }

  private getRequestUrl(HttpServletRequest request) {

    if(org.springframework.util.StringUtils.hasText(request.queryString))

    request.requestURL.append('?').append(request.queryString)


    return request.requestURL.toString()
  }

  private createAjaxRedirectXml(String redirectUrl) {

    return new StringBuilder().append('<?xml version=\'1.0\' encoding=\'UTF-8\'?>')
                              .append('<partial-response><redirect url=\'')
                              .append(redirectUrl)
                              .append('\'></redirect></partial-response>')
                              .toString()
  }

}